package com.collect.senegal.zhiScene.zhiWidget.zhiCutdown;

import android.content.Context;
import android.util.AttributeSet;

import androidx.annotation.Nullable;

public class ZHITimerTextView extends androidx.appcompat.widget.AppCompatTextView implements Runnable {

    public OnTimerCompleted mOnTimerCompleted;
    public boolean mRuning = false; //是否启动了
    public int mSeconds = 30;

    public ZHITimerTextView(Context context) {
        super(context);
    }

    public ZHITimerTextView(Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ZHITimerTextView(Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void run() {
        if (mRuning) {
            mSeconds -= 1;

            String strTime = mSeconds + "s";
            this.setText(strTime);

            if (mSeconds <= 0) {
                mSeconds = 30;
                stopRun();
                if (mOnTimerCompleted != null) {
                    postDelayed(() -> {
                        if (mOnTimerCompleted != null) {
                            mOnTimerCompleted.onFinish();
                        }
                    }, 500);
                }
                return;
            }

            postDelayed(this, 1000);
        } else {
            removeCallbacks(this);
        }
    }

    public boolean isRun() {
        return mRuning;
    }

    public void beginRun() {
        this.mRuning = true;
        run();
    }

    public void stopRun() {
        this.mRuning = false;
        removeCallbacks(this);
    }

    public void setOnTimerCompleted(OnTimerCompleted onTimerCompleted){
        this.mOnTimerCompleted = onTimerCompleted;
    }

    public interface OnTimerCompleted {
        void onFinish();
    }
}
